{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gym\n",
    "\n",
    "\n",
    "#定义环境\n",
    "class MyWrapper(gym.Wrapper):\n",
    "\n",
    "    def __init__(self):\n",
    "        env = gym.make('CartPole-v1', render_mode='rgb_array')\n",
    "        super().__init__(env)\n",
    "        self.env = env\n",
    "        self.step_n = 0\n",
    "\n",
    "    def reset(self, seed=None, options=None):\n",
    "        self.step_n = 0\n",
    "        return self.env.reset()\n",
    "\n",
    "    def step(self, action):\n",
    "        self.step_n += 1\n",
    "        state, reward, truncated, terminated, info = self.env.step(action)\n",
    "\n",
    "        if self.step_n >= 200:\n",
    "            truncated = True\n",
    "            terminated = True\n",
    "\n",
    "        return state, reward, truncated, terminated, info\n",
    "\n",
    "    #打印游戏图像\n",
    "    def show(self):\n",
    "        from matplotlib import pyplot as plt\n",
    "        plt.figure(figsize=(3, 3))\n",
    "        plt.imshow(self.env.render())\n",
    "        plt.show()\n",
    "\n",
    "\n",
    "env = MyWrapper()\n",
    "env.reset()\n",
    "\n",
    "env.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "543OHYDfcjK4"
   },
   "outputs": [],
   "source": [
    "from stable_baselines3.common.env_util import make_vec_env\n",
    "from stable_baselines3 import PPO\n",
    "from stable_baselines3.common.evaluation import evaluate_policy\n",
    "\n",
    "#初始化模型\n",
    "model = PPO(policy='MlpPolicy',\n",
    "            env=make_vec_env(MyWrapper, n_envs=4),\n",
    "            n_steps=200,\n",
    "            batch_size=64,\n",
    "            n_epochs=4,\n",
    "            gamma=0.999,\n",
    "            gae_lambda=0.98,\n",
    "            ent_coef=0.01,\n",
    "            verbose=0)\n",
    "\n",
    "#测试\n",
    "evaluate_policy(model, env, n_eval_episodes=20, deterministic=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "#训练\n",
    "model.learn(total_timesteps=50, progress_bar=True)\n",
    "\n",
    "model.save('models/ppo-CartPole-v1')\n",
    "model = PPO.load('models/ppo-CartPole-v1')\n",
    "\n",
    "evaluate_policy(model, env, n_eval_episodes=20, deterministic=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython import display\n",
    "import random\n",
    "\n",
    "\n",
    "def play():\n",
    "    state, _ = env.reset()\n",
    "    over = False\n",
    "    reward_sum = 0\n",
    "\n",
    "    while not over:\n",
    "        action, _ = model.predict(state)\n",
    "\n",
    "        state, reward, truncated, terminated, _ = env.step(action)\n",
    "        over = truncated or terminated\n",
    "        reward_sum += reward\n",
    "\n",
    "        #跳帧\n",
    "        if random.random() < 0.2:\n",
    "            display.clear_output(wait=True)\n",
    "            env.show()\n",
    "\n",
    "    return reward_sum\n",
    "\n",
    "\n",
    "play()"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "include_colab_link": true,
   "name": "Copie de Unit 1: Train your first Deep Reinforcement Learning Agent 🚀.ipynb",
   "private_outputs": true,
   "provenance": []
  },
  "gpuClass": "standard",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
